var _global;
var _framerate = require('tools/framerate.js');
var _gl = require('opengl');
var _geometry = require('core/glm.js');
var _glm = _geometry.glm;
var _inherit = require('core/inherit.js');

var _prefer = require('game/prefer.js').prefer;
var firstInit = true;

// ==========================
// SceneAdapter
// ==========================
/**
 * wire all scenes switch
 * @constructor
 */
function SceneAdapter() {
}
SceneAdapter.prototype.coverLoadingFinish = function (loaidng) {
    var screenAdapter = _global.mScreenAdapter;
    var levelsel = require('scenes/levelselect.js').newInstance(screenAdapter.mWidth, screenAdapter.mHeight);
    _global.registerScene('levelsel', levelsel);
    _global.unregisterScene(loaidng);
};
SceneAdapter.prototype.listen = function (scene, event, callback) {
    scene.on(event, this[callback], this);
};

//var cover = require('scenes/levelselect.js').newInstance(screenAdapter.mWidth, screenAdapter.mHeight);
//var cover = require('scenes/leveltarget.js').newInstance(screenAdapter.mWidth, screenAdapter.mHeight);
// ==========================
// Game
// ==========================
function Game() {
    console.log('function Game');
    this.mScenes = new SceneAdapter();
}
Game.prototype.onSurfaceCreated = function (width, height) {
    if (!firstInit) {
        return;
    }

    _global = require('game/global.js');
    _gl.clearColor(1, 1, 1, 0);

    _gl.enable(_gl.BLEND);
    _gl.blendFunc(_gl.ONE, _gl.ONE_MINUS_SRC_ALPHA);

    _gl.disable(_gl.DEPTH_TEST);
    _gl.disable(_gl.STENCIL_TEST);
    _gl.disable(_gl.SCISSOR_TEST);

    _global.onScreenSizeChange(width, height);
    var screenAdapter = _global.mScreenAdapter;
    var loading = require('scenes/game.js').newInstance(screenAdapter.mWidth, screenAdapter.mHeight);
//    var loading = require('scenes/game.js').newInstance(screenAdapter.mWidth, screenAdapter.mHeight);
//    var loading = require('scenes/coverloading.js').newInstance(screenAdapter.mWidth, screenAdapter.mHeight);
    this.mScenes.listen(loading, 'finish', 'coverLoadingFinish');
    _global.registerScene('coverloading', loading);

    firstInit = false;
};
Game.prototype.onSurfaceChanged = function (width, height) {
    _global.onScreenSizeChange(width, height);
};
Game.prototype.onDrawFrame = function () {
    _global.runSchedule();
    //_framerate.update();
};
Game.prototype.pause = function () {
    console.log('Game.prototype.pause=>');
};
Game.prototype.resume = function () {
    console.log('Game.prototype.resume=>');
};

var game = new Game();
function wrap(obj, name) {
    var fn = obj[name];
    obj[name] = function () {
        try {
            fn.apply(obj, arguments);
        } catch (e) {
            console.log(name + '.exception:' + e);
        }
    }
}
for (var i in game.render) {
    wrap(game.render, i);
}

module.exports = game;
